<template>
  <div style="" v-if="rowInfo">
    <el-dialog width="40%" top="10vh" :visible.sync="dialogVisible" :close-on-click-modal="false" destroy-on-close @close="dialogShow(false)">
      <div slot="title" class="dialog_title">
        <div class="title_name">Publish Project</div>
      </div>
      <div  class="dialog-content">
        <div class="quit-tip"> Before publishing your project, please ensure that the following meatdata is correct. </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
          <el-row>
            <el-col :span="24">
              <el-form-item label="Description" prop="">
                <el-input class="ms-bg-gray" type="textarea"
                  :rows="3"
                  placeholder="Type description here..."
                  maxlength="120"
                  show-word-limit
                  v-model="ruleForm.description"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="Genre" prop="genre">
                <el-select class="ms-bg-gray" style="width: 100%;" :popper-append-to-body='false' multiple v-model="ruleForm.genre">
                  <el-option v-for="(item, i) in genreOptions"
                    :key="i"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Duration (min)" prop="duration">
                <el-input-number  class="ms-bg-gray" style="width: 100%;"
                  v-model="ruleForm.duration" controls-position="right" :min="0"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Age Demographic" prop="demographic">
                <el-select class="ms-bg-gray" style="width: 100%;" :popper-append-to-body='false' multiple v-model="ruleForm.demographic">
                  <el-option v-for="(item, i) in demographicOptions"
                    :key="i"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Language" prop="language">
                <el-select class="ms-bg-gray" style="width: 100%;" :popper-append-to-body='false' v-model="ruleForm.language">
                  <el-option v-for="(item, i) in languageOptions"
                    :key="i"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Category" prop="category">
                <el-select class="ms-bg-gray" style="width: 100%;" :popper-append-to-body='false' v-model="ruleForm.category">
                  <el-option v-for="(item, i) in categoryOptions"
                    :key="i"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Poster" prop="poster_fileName">
                <div class="form-item-upload">
                  <el-tooltip class="item" effect="dark" :content="poster.name">
                    <span class="input-upload-file-name">{{poster.name}}</span>
                  </el-tooltip>
                  <el-upload
                    class="input-upload-btn"
                    :auto-upload="false"
                    action=""
                    accept="image/png,image/jpeg"
                    :show-file-list="false"
                    :on-change="posterUpload"
                  >
                    <el-button size="mini" :loading="posterUploadLoading">Upload</el-button>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Concept Art (optional)" prop="">
                <div class="form-item-upload">
                  <el-tooltip class="item" effect="dark" :content="conceptArt.name">
                    <span class="input-upload-file-name">{{conceptArt.name}}</span>
                  </el-tooltip>
                  <el-upload
                    class="input-upload-btn"
                    :auto-upload="false"
                    action=""
                    accept="image/png,image/jpeg"
                    :show-file-list="false"
                    :on-change="conceptArtUpload"
                  >
                    <el-button size="mini" :loading="conceptArtUploadLoading">Upload</el-button>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" round type="text">Cancel</el-button>
        <el-button @click="e => {handleOk(e)}" type="primary" round>Send</el-button>
      </div>
    </el-dialog>

    <el-dialog width="400px"
      :visible.sync="dialogVisible_pay"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div slot="title" class="select_audio_title">
        <div style="font-size: 18px; text-align: center; padding: 20px; font-weight: bold; color: #6e6e6e;">
          Insufficient balance
        </div>
      </div>
      <div>
        <div style="font-size: 14px; padding: 20px; color: #6e6e6e; text-align: center;">
          Missing amount : <span style="font-size: 21px; color: #6e6e6e; font-weight: bold;"> ${{missingAmount}} </span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <div @click="goTopUp" class="btn_ok">Go top up</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cookie from 'js-cookie';
export default {
  props: {},
  watch: {},
  data() {
    return {
      dialogVisible: false,
      dialogVisible_pay: false,
      missingAmount: 0,
      payUrl: '',
      userId: cookie.get('username'),
      rowInfo: null,
      ruleForm: {
        duration: 0,
        genre: '',
        demographic: '',
        language: '',
        category: '',
        description: '',
        poster_fileName: '',
        conceptArt_fileName: '',
      },
      poster: {},
      conceptArt: {},
      posterUploadLoading: false,
      conceptArtUploadLoading: false,
      rules: {
        duration: [
          { required: true, message: 'Please input the duration', trigger: 'blur' }
        ],
        demographic: [
          { required: true, message: 'Please select age demographic', trigger: 'blur' }
        ],
        genre: [
          { required: true, message: 'Please select genre', trigger: 'blur' }
        ],
        language: [
          { required: true, message: 'Please slect language', trigger: 'change' }
        ],
        category: [
          { required: true, message: 'Please slect category', trigger: 'change' }
        ],
        poster_fileName: [
          { required: true, message: 'Please upload poster image', trigger: 'change' }
        ],
      },
      genreOptions: [],
      demographicOptions: [],
      languageOptions: [],
      categoryOptions: [],
    };
  },
  created() {},
  mounted() {},
  methods: {
    // 弹窗 显示 或 隐藏
    dialogShow(show, row) {
      this.dialogVisible = show;
      this.ruleForm.reason = '';
      if (show) {
        this.rowInfo = row;
        this.getGenreOptions();
        this.getDemographicOptions();
        this.getLanguageOptions();
        this.getCategoryOptions();
      } else {
        this.ruleForm = {
          duration: 0,
          genre: '',
          demographic: '',
          language: '',
          category: '',
          description: '',
          poster_fileName: '',
          conceptArt_fileName: '',
        }
      }
    },

    handleOk(e) {
      e && e.stopPropagation();
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const params = {
            id: this.rowInfo.projectId,
            userId: this.userId,
            completed: true,
            published: true,
            posterPath: this.poster.url,
            conceptArt: this.conceptArt.url,
            duration: this.ruleForm.duration,
            genres: this.ruleForm.genre,
            demographics: this.ruleForm.demographic,
            languageId: this.ruleForm.language,
            categoryId: this.ruleForm.category,
            description: this.ruleForm.description,
          }
          this.$api.apiModules.publishProject(this.userId, this.rowInfo.projectId, params).then(res => {
            if (res.status === 200) {
              this.$message.success(`Operation successful`);
              this.$emit('dialogClickOK', this.rowInfo);
              this.dialogVisible = false;
            }
          }).catch(error => {
            const res = error.response.data;
            // 如果余额不足
            if ( res.errorCode == 402 && res.moreInfo && res.moreInfo !== '' ){
              this.missingAmount = JSON.parse(res.moreInfo).gap.toFixed(2);
              this.dialogVisible_pay = true;
              const url = window.location.origin;
              const payPamars = {
                cancelUrl: url + '/pay/error',
                returnUrl: url + '/pay/success',
                currency: 'USD',
                username: this.userId,
                value: this.missingAmount,
                description: '',
                projectId: this.rowInfo.projectId,
              }
              this.$api.apiModules.paymentCheckout(this.userId, payPamars).then(res => {
                if (res.data && res.data.links) {
                  res.data.links.forEach((item) => {
                    if (item.rel === 'approve') {
                      item.issss = 1;
                      this.payUrl = item.href;
                    }
                  });
                  //为了给支付成功失败使用的
                  this.payInfo = {
                    paypayUrl: this.payUrl,
                    projectName: this.rowInfo.projectResponse.name,
                    projectStartTime: this.rowInfo.projectResponse.startingTime,
                    projectEndTime: this.rowInfo.projectResponse.endingTime,
                    orderId: res.data.id,
                    type: 2,
                  };
                  Cookies.set('projectPayInfo', JSON.stringify(this.payInfo));
                }
              });

            } else {
              this.$message.error('Error' + res.errorMessage);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    goTopUp() {
      window.open(this.payUrl, "_self");
    },

    async posterUpload(file) {
      this.posterUploadLoading = true;
      const r1 = await this.$api.apiModules.getS3UrlByFileName(file.name);
      if (r1.status !== 200 || !r1.data?.presignedUrl) return;
      this.poster = {
        name: file.name,
        url: r1.data.path,
      };
      this.$api.apiModules.uploadImgToS3Url(r1.data.presignedUrl, file.raw).then(res => {
        if (res.status === 200) {
          this.$message.success(`Upload successful`);
          this.posterUploadLoading = false;
          this.ruleForm.poster_fileName = file.name;
        };
      }).catch(error => {
        this.$message.error(`Upload failed`);
        this.posterUploadLoading = false;
        this.poster = {};
      });
    },
    async conceptArtUpload(file) {
      this.conceptArtUploadLoading = true;
      const r1 = await this.$api.apiModules.getS3UrlByFileName(file.name);
      if (r1.status !== 200 || !r1.data?.presignedUrl) return;
      this.conceptArt = {
        name: file.name,
        url: r1.data.path,
      };
      this.$api.apiModules.uploadImgToS3Url(r1.data.presignedUrl, file.raw).then(res => {
        if (res.status === 200) {
          this.$message.success(`Upload successful`);
          this.conceptArtUploadLoading = false;
          this.ruleForm.conceptArt_fileName = file.name;
        };
      }).catch(error => {
        this.$message.error(`Upload failed`);
        this.conceptArtUploadLoading = false;
        this.conceptArt = {};
      });
    },

    async getGenreOptions() {
      const res = await this.$api.apiModules.getGenreOptions(this.userId);
      if (res.status !== 200) return;
      this.genreOptions = res.data.Genres;
    },
    async getDemographicOptions() {
      const res = await this.$api.apiModules.getDemographicOptions(this.userId);
      if (res.status !== 200) return;
      this.demographicOptions = res.data.Demographic;
    },
    async getLanguageOptions() {
      const res = await this.$api.apiModules.getLanguageOptions(this.userId);
      if (res.status !== 200) return;
      this.languageOptions = res.data.language;
    },
    async getCategoryOptions() {
      const res = await this.$api.apiModules.getCategoryOptions(this.userId);
      if (res.status !== 200) return;
      this.categoryOptions = res.data.category;
    },
  }
};
</script>

<style lang="less" scoped>
.dialog_title {
  display: flex;
  align-items: center;
  font-size: 16px;
  justify-content: center;
  .title_name{
    font-weight: bold;
    color: #5a5a5a;
  }
  .title_icon {
    width: 28px;
    height: 28px;
    margin-right: 10px;
  }
}
.dialog-content{
  padding: 0 20px;
  min-height: 500px;
  position: relative;

  .form-item-upload{
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f2f2f2;
    height: 40px;
    border-radius: 4px;
    position: relative;
    padding: 0 6px;
    .input-upload-btn{
      display: inline-block;
    }
    .input-upload-file-name{
      flex: 1;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      padding: 0 10px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}

/deep/ .el-dialog {
  border-radius: 24px;
}

/deep/ .el-table__header-wrapper {
  .el-checkbox {
    display: none;
  }
}

.ms-bg-gray{
  /deep/ .el-input__inner,
  /deep/ .el-textarea__inner,
  /deep/ .el-input__count{
    background: #f2f2f2;
    border-color: #f2f2f2;
  }
}

</style>
